package cn.com.dycc.common.attach.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.util.JsonResult;
import cn.com.dycc.util.PathUtil;

@Service("attachService")
public class AttachServiceImpl implements AttachService{
	
	@Resource(name="attachDao")
	private AttachDao attachDao;
	
	//插入附件
	public JsonResult insertAttach(Attach attach) throws NotFoundAttachException {
		
		int addAttach = attachDao.insertAttach(attach);
		JsonResult jr = new JsonResult();
		if(addAttach<=0){
			jr.setState(0);
			jr.setMessage("插入附件失败！");
		}else{
			jr.setState(1);
			jr.setData("插入附件成功！");
		}
		return jr;
	}
	
	//附件序列
	public String findAttach_path_seq() throws NotFoundAttachException {
		
		String attach_path = attachDao.findAttach_path_seq();
		if(attach_path==null){
			throw new NotFoundAttachException("附件路径不能为空！");
		}
		return attach_path;
	}
	
	//获取附件id
	public Attach getAttach(String id,HttpServletRequest request) throws NotFoundAttachException {
		if(id==null){
			throw new NotFoundAttachException("附件id不能为空");
		}
		String org_id = request.getSession().getAttribute("org_id").toString();
		Attach attach  = attachDao.getAttach(id,org_id);
		return attach;
	}
	
	// 根据messge_no和附件类型获取附件
	public List<Attach> findAttachByMesNoAndType(String message_no, Integer attach_type,HttpServletRequest request)
			throws NotFoundAttachException {
		if(message_no==null){
			throw new NotFoundAttachException("请选择需要查询的关联模块id");
		}
		if(attach_type==null){
			throw new NotFoundAttachException("请输入选择查询的模块对应类型");
		}
		String org_id = request.getSession().getAttribute("org_id").toString();
		List<Attach> list = new ArrayList<Attach>();
		try {
			list = attachDao.findAttachByMesNoAndType(message_no, attach_type,org_id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NotFoundAttachException("查询失败！");
		}
		return list;
	}
	
	//删除附件信息
	public String delAttach(HttpServletRequest request,String id) throws NotFoundAttachException {
		
		if(id==null||id.trim().isEmpty()){
			throw new NotFoundAttachException("请选择需要删除的附件！");
		}
		
		String path  = attachDao.findPath(id);
		if(path==null){
			throw new NotFoundAttachException("附件未存在！");
		}
		String org_id = request.getSession().getAttribute("org_id").toString();
//		System.out.println(path);
		File filepath = new File(path); 
		int del = attachDao.delAttach(id,org_id);
        if(del==0){
        	throw new NotFoundAttachException("删除失败！");  
        }
        if(filepath.exists()){//判断改路径是否存在  
        	filepath.delete();
        }
       
		return "删除成功！";
	}	

}
